/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package struts;


import Service.PlanService;
import Service.PlanServiceImpl;
import java.io.BufferedReader;
import java.util.*;
import javabeans.Event;
import javabeans.Plan;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


/**
 *
 * @author jo
 */
public class PlanAction extends Action{

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-store"); //HTTP1.1
        response.setHeader("Pragma", "no-cache"); //HTTP1.0
        response.setDateHeader("Expires", 0); //prevents catching at proxy server

        String action = request.getParameter("action");

        if("updatePlan".equals(action)){
System.out.println("update plan");
            
            //check the database
            boolean updatePlanSuccess = true;
System.out.println(updatePlanSuccess);

            response.setContentType("text/json");
            if(updatePlanSuccess == true) {
                response.getWriter().write("{ success: true, errors:{} }");
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }
        } else if("loadPlan".equals(action)){
System.out.println("load plan");
            int planid = Integer.parseInt(request.getParameter("planid"));
System.out.println(planid);
            PlanService ps = new PlanServiceImpl();
            //check the database
            Plan plan = ps.getPlan(planid);
            
            boolean loadPlanSuccess = true;
            if(plan == null) {
                loadPlanSuccess = false;
            }
            
System.out.println(loadPlanSuccess);
System.err.println("events: " + plan.getEvents().size());
            Map <String, Class> m = new HashMap <String, Class>();
            //m.put("eventInfos", EventInfo.class);
            JsonConfig config = new JsonConfig();
            config.setJsonPropertyFilter(new PropertyFilter(){
                public boolean apply(Object source, String name, Object value) {
                    if(name.equals("plan")||name.equals("planindex")||name.equals("member")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            JSONObject jsonObject = JSONObject.fromObject(plan, config);
System.out.println(jsonObject);

            response.setContentType("text/json");
            if(loadPlanSuccess == true) {
                //String resp = "{'events':[{'color':'red','eventdate':'asdasd','eventdescript':'my event1','eventname':'event1','eventtime':'123','id':1001,'plan':null,'pointX':1.212,'pointY':121212.333,'type':'hotel'},{'color':'green','eventdate':'','eventdescript':'my event2','eventname':'event2','eventtime':'','id':1002,'plan':null,'pointX':0,'pointY':0,'type':null}],'plandescript':'my plan','planid':123,'planname':'plan1'}";
                String resp = jsonObject.toString();
                response.getWriter().write(resp);
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }
        } else if("savePlan".equals(action)) {
System.out.println("save plan");
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            try {
                BufferedReader reader = request.getReader();
                while ((line = reader.readLine()) != null)
                    stringBuffer.append(line);
            } catch (Exception e) { }//report an error }
System.out.println(stringBuffer);
            String str = stringBuffer.toString();
            //String str = "{\"planid\":42,\"planname\":\"asd\",\"plandescript\":\"asd\",\"eventInfos\":[{\"operation\":\"new\",\"event\":{\"id\":\"\",\"eventname\":\"1111\",\"type\":\"12\",\"pointX\":\"121\",\"pointY\":\"212\",\"eventdate\":\"12/01/2009\",\"eventtime\":\"3:15 AM\",\"color\":\"1212\",\"eventdescript\":\"1212\"}}]}";
            JSONObject jsonObject = JSONObject.fromObject(str);
            Map <String, Class> m = new HashMap <String, Class>();
            m.put("eventInfos", EventInfo.class);
            m.put("event", Event.class);
            PlanInfo planInfo = (PlanInfo) JSONObject.toBean(jsonObject, PlanInfo.class, m);
            planInfo.saveThisPlan();
            //save to database
            boolean savePlanSuccess = true;

            response.setContentType("text/json");
            if(savePlanSuccess == true) {
                response.getWriter().write("{ success: true }");
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }       
        } else if("deletePlan".equals(action)) {
System.out.println("delete plan");
            int planid = Integer.parseInt(request.getParameter("planid"));
System.out.println(planid);
            PlanService ps = new PlanServiceImpl();         
            boolean deletePlanSuccess = ps.deletePlan(planid);

            response.setContentType("text/json");
            if(deletePlanSuccess == true) {
                response.getWriter().write("{ success: true }");
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }
            
        }
       return super.execute(mapping, form, request, response);
    }

}
